<template>
  <el-drawer
    v-model="visible"
    title="智能过滤设置"
    direction="rtl"
    size="700px"
    :before-close="handleClose"
  >
    <div class="filter-container">
      <el-alert
        title="智能过滤可以帮助您自动识别并过滤掉不需要的银行流水记录"
        type="info"
        show-icon
        style="margin-bottom: 20px;"
      />

      <el-tabs v-model="activeTab">
        <!-- 预设规则 -->
        <el-tab-pane label="预设规则" name="preset">
          <div class="preset-rules">
            <el-card 
              v-for="rule in presetRules" 
              :key="rule.id" 
              class="rule-card"
              :class="{ 'rule-active': rule.enabled }"
            >
              <div class="rule-header">
                <el-checkbox v-model="rule.enabled" @change="handleRuleChange(rule)">
                  {{ rule.name }}
                </el-checkbox>
                <el-tag :type="getRuleType(rule.type)" size="small">
                  {{ getRuleTypeName(rule.type) }}
                </el-tag>
              </div>
              <div class="rule-content">
                <div class="rule-condition">
                  <strong>条件：</strong>{{ rule.condition }}
                </div>
                <div class="rule-description">
                  {{ rule.description }}
                </div>
              </div>
              <div class="rule-actions">
                <el-button link @click="editRule(rule)">编辑</el-button>
                <el-button link @click="deleteRule(rule)" type="danger">删除</el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 自定义规则 -->
        <el-tab-pane label="自定义规则" name="custom">
          <div class="custom-rules">
            <el-button type="primary" @click="showRuleForm" style="margin-bottom: 15px;">
              <el-icon><plus /></el-icon>
              添加自定义规则
            </el-button>

            <el-table :data="customRules" style="width: 100%">
              <el-table-column prop="name" label="规则名称" width="150" />
              <el-table-column prop="condition" label="过滤条件" />
              <el-table-column prop="priority" label="优先级" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPriorityType(row.priority)">
                    {{ getPriorityText(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template #default="{ row }">
                  <el-switch 
                    v-model="row.enabled" 
                    @change="handleRuleChange(row)"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button link @click="editRule(row)">编辑</el-button>
                  <el-button link @click="deleteRule(row)" type="danger">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 规则测试 -->
        <el-tab-pane label="规则测试" name="test">
          <div class="rule-test">
            <el-alert
              title="您可以在这里测试规则是否按预期工作"
              type="warning"
              show-icon
              style="margin-bottom: 20px;"
            />

            <el-form :model="testForm" label-width="100px">
              <el-form-item label="测试文本">
                <el-input 
                  v-model="testForm.text" 
                  placeholder="请输入要测试的文本，如付款方名称或交易备注"
                  clearable
                />
              </el-form-item>
              <el-form-item label="匹配规则">
                <el-select v-model="testForm.ruleId" placeholder="请选择规则" class="form-item-width">
                  <el-option label="所有启用规则" value="" />
                  <el-option 
                    v-for="rule in allEnabledRules" 
                    :key="rule.id" 
                    :label="rule.name" 
                    :value="rule.id" 
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="testRule">测试规则</el-button>
              </el-form-item>
            </el-form>

            <div v-if="testResult" class="test-result">
              <el-divider />
              <h4>测试结果</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="测试文本">{{ testResult.text }}</el-descriptions-item>
                <el-descriptions-item label="匹配规则">{{ testResult.ruleName || '无匹配' }}</el-descriptions-item>
                <el-descriptions-item label="是否过滤">
                  <el-tag :type="testResult.willFilter ? 'danger' : 'success'">
                    {{ testResult.willFilter ? '是' : '否' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="匹配详情" v-if="testResult.matchedText">
                  匹配到：{{ testResult.matchedText }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveRules">保存设置</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 规则编辑对话框 -->
  <el-dialog
    v-model="ruleFormVisible"
    :title="editingRule ? '编辑规则' : '添加规则'"
    width="500px"
  >
    <el-form :model="ruleForm" label-width="80px">
      <el-form-item label="规则名称" required>
        <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
      </el-form-item>
      <el-form-item label="过滤条件" required>
        <el-input v-model="ruleForm.condition" placeholder="请输入过滤条件，支持正则表达式" />
      </el-form-item>
      <el-form-item label="规则类型">
        <el-select v-model="ruleForm.type" class="form-item-width">
          <el-option label="包含关键词" value="keyword" />
          <el-option label="正则匹配" value="regex" />
          <el-option label="金额范围" value="amount" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级">
        <el-select v-model="ruleForm.priority" class="form-item-width">
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input 
          v-model="ruleForm.description" 
          type="textarea" 
          placeholder="请输入规则描述"
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ruleFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRule">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'rules-updated', rules: any[]): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const activeTab = ref('preset')
const ruleFormVisible = ref(false)
const editingRule = ref<any>(null)

const presetRules = ref([
  {
    id: '1',
    name: '过滤工资收入',
    type: 'keyword',
    condition: '包含"工资","薪资","薪酬"',
    description: '自动过滤工资收入类流水',
    enabled: true
  },
  {
    id: '2',
    name: '过滤内部转账',
    type: 'keyword',
    condition: '包含"内部转账","公司转账"',
    description: '自动过滤公司内部转账流水',
    enabled: true
  },
  {
    id: '3',
    name: '过滤退款交易',
    type: 'keyword',
    condition: '包含"退款","退货","退款"',
    description: '自动过滤退款类流水',
    enabled: false
  },
  {
    id: '4',
    name: '过滤大额转账',
    type: 'amount',
    condition: '金额大于100000',
    description: '自动过滤大额转账流水（可自定义金额）',
    enabled: false
  }
])

const customRules = ref([
  {
    id: '101',
    name: '过滤奖金收入',
    type: 'keyword',
    condition: '包含"奖金","奖励","提成"',
    description: '过滤奖金类收入流水',
    priority: 'medium',
    enabled: true
  },
  {
    id: '102',
    name: '过滤报销款项',
    type: 'keyword',
    condition: '包含"报销","差旅费","办公费"',
    description: '过滤员工报销类流水',
    priority: 'high',
    enabled: true
  }
])

const testForm = reactive({
  text: '',
  ruleId: ''
})

const testResult = ref<any>(null)

const ruleForm = reactive({
  name: '',
  condition: '',
  type: 'keyword',
  priority: 'medium',
  description: ''
})

const allEnabledRules = computed(() => {
  return [...presetRules.value, ...customRules.value].filter(rule => rule.enabled)
})

const getRuleType = (type: string) => {
  const typeMap: Record<string, any> = {
    keyword: 'primary',
    regex: 'success',
    amount: 'warning'
  }
  return typeMap[type] || 'info'
}

const getRuleTypeName = (type: string) => {
  const nameMap: Record<string, string> = {
    keyword: '关键词',
    regex: '正则',
    amount: '金额'
  }
  return nameMap[type] || '未知'
}

const getPriorityType = (priority: string) => {
  const typeMap: Record<string, any> = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return textMap[priority] || '未知'
}

const handleRuleChange = (rule: any) => {
  ElMessage.success(`${rule.enabled ? '启用' : '禁用'}规则：${rule.name}`)
}

const editRule = (rule: any) => {
  editingRule.value = rule
  Object.assign(ruleForm, rule)
  ruleFormVisible.value = true
}

const deleteRule = (rule: any) => {
  ElMessageBox.confirm(`确定要删除规则"${rule.name}"吗？`, '删除规则', {
    type: 'warning'
  }).then(() => {
    if (presetRules.value.includes(rule)) {
      presetRules.value = presetRules.value.filter(r => r.id !== rule.id)
    } else {
      customRules.value = customRules.value.filter(r => r.id !== rule.id)
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const showRuleForm = () => {
  editingRule.value = null
  Object.assign(ruleForm, {
    name: '',
    condition: '',
    type: 'keyword',
    priority: 'medium',
    description: ''
  })
  ruleFormVisible.value = true
}

const saveRule = () => {
  if (!ruleForm.name || !ruleForm.condition) {
    ElMessage.warning('请填写规则名称和条件')
    return
  }

  if (editingRule.value) {
    Object.assign(editingRule.value, ruleForm)
    ElMessage.success('规则更新成功')
  } else {
    const newRule = {
      id: `custom_${Date.now()}`,
      ...ruleForm,
      enabled: true
    }
    customRules.value.push(newRule)
    ElMessage.success('规则添加成功')
  }

  ruleFormVisible.value = false
}

const testRule = () => {
  if (!testForm.text) {
    ElMessage.warning('请输入测试文本')
    return
  }

  let matchedRule = null
  let matchedText = ''

  // 获取要测试的规则
  const rulesToTest = testForm.ruleId 
    ? [...presetRules.value, ...customRules.value].filter(r => r.id === testForm.ruleId)
    : allEnabledRules.value

  // 测试规则
  for (const rule of rulesToTest) {
    if (rule.type === 'keyword') {
      const keywords = rule.condition.replace(/包含/g, '').replace(/"/g, '').split(/[,，]/)
      for (const keyword of keywords) {
        if (testForm.text.includes(keyword.trim())) {
          matchedRule = rule
          matchedText = keyword.trim()
          break
        }
      }
    } else if (rule.type === 'regex') {
      try {
        const regex = new RegExp(rule.condition)
        const match = testForm.text.match(regex)
        if (match) {
          matchedRule = rule
          matchedText = match[0]
          break
        }
      } catch (e) {
        console.error('正则表达式错误:', e)
      }
    }
    
    if (matchedRule) break
  }

  testResult.value = {
    text: testForm.text,
    ruleName: matchedRule?.name || '',
    willFilter: !!matchedRule,
    matchedText: matchedText
  }

  ElMessage.success('测试完成')
}

const saveRules = () => {
  const allRules = [...presetRules.value, ...customRules.value]
  emit('rules-updated', allRules)
  handleClose()
  ElMessage.success('保存成功')
}

const handleClose = () => {
  visible.value = false
  testResult.value = null
  Object.assign(testForm, {
    text: '',
    ruleId: ''
  })
}
</script>

<style scoped lang="scss">
.rule-card {
  margin-bottom: 15px;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  &.rule-active {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.rule-content {
  margin-bottom: 15px;
  
  .rule-condition {
    margin-bottom: 8px;
    color: #606266;
  }
  
  .rule-description {
    color: #909399;
    font-size: 13px;
  }
}

.rule-actions {
  text-align: right;
}

.test-result {
  margin-top: 20px;
}

.form-item-width {
  width: 100%;
}
</style>